﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRepository;
using Infrastructures;
using EFModels;
using System.Data.Entity;

namespace RepositoryEF
{
    public class CommonRepository : ICommonRepository
    {
        internal CommonRepository() { }

        public virtual T Create<T>(T obj)
        {
            using (bingoEntities entity = new bingoEntities())
            {
                entity.Set(obj.GetType()).Add(obj);
                entity.SaveChanges();
            };

            return obj;
        }

        public virtual void Update<T>(T obj)
        {
            using (bingoEntities entity = new bingoEntities())
            {
                var modifiedEntity = entity.Entry((object)obj);
                entity.Set(obj.GetType()).Attach(obj);
                modifiedEntity.State = EntityState.Modified;
                entity.SaveChanges();
            };
        }

        public virtual void Delete<T>(string code)
        {
            using (bingoEntities entity = new bingoEntities())
            {
                Type type = typeof(T);

                var obj = entity.Set(type).Find(code.ToInt());
                if (obj != null)
                {
                    entity.Set(type).Remove(obj);
                    entity.SaveChanges();
                }
            }
        }

        public virtual List<T> List<T>()
        {
            //using (bingoEntities entity = new bingoEntities())
            //{
            //    return entity.user_info.ToList() as List<T>;
            //}

            return null;
        }

        public virtual T Get<T>(string code)
        {
            using (bingoEntities entity = new bingoEntities())
            {
                return (T)entity.Set(typeof(T)).Find(code.ToInt());
            }
        }
    }
}
